package com.yan.ems.interceptor;
import com.yan.ems.utils.TokenGenerator;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

//@Component
public class LoginInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
		String authorizationHeader = request.getHeader("Authorization");
		String contentType = request.getHeader("Content-Type");
		String connection = request.getHeader("Connection");

		System.out.println("authorizationHeader: " + authorizationHeader);
		System.out.println("contentType: " + contentType);
		System.out.println("connection: " + connection);

		if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
			// 提取实际的 Token
			String token = authorizationHeader.substring(7);
			if (TokenGenerator.validateToken(token)) {
				return true;
			}
			throw new RuntimeException("登录状态过期，请重新登录");
		}

		response.sendRedirect("/login");
		return false;
	}
}
